package com.example.myone.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myone.Entity.User;
import com.example.myone.Mapper.UserMapper;
import com.example.myone.R;
import com.example.myone.Util.ClickUtils;
import com.example.myone.Util.ImageUtils;
import com.example.myone.Util.PasswordEncryptor;

public class RegisterActivity extends AppCompatActivity {

    private EditText accountEdit;
    private EditText passwordEdit;
    private Button registerButton;
    private TextView toLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_activity);

        accountEdit = findViewById(R.id.account);
        passwordEdit = findViewById(R.id.password);
        registerButton = findViewById(R.id.register_button);
        toLogin = (TextView) findViewById(R.id.toLogin);

        View registerLogo = findViewById(R.id.register_logo);
        ClickUtils.setClickListener(this, registerLogo,null, this::finish);
        // 设置跳转登录点击事件
        ClickUtils.setClickListener(this, toLogin, "前往登录", () -> {
            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        });
        // 注册按钮的点击事件
        registerButton.setOnClickListener(v -> {
            // 获取用户输入的用户名和密码
            String account = accountEdit.getText().toString();
            String password = passwordEdit.getText().toString();

            if (!account.isEmpty() && !password.isEmpty()) { // 检查用户名和密码是否非空
                // 调用 saveAccount() 方法保存账号和密码
                if (saveAccount(account, password)) {// 显示注册成功的提示信息
                    Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                    // 跳转到登录页面
                    Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        });
    }

    // 保存账号密码
    private boolean saveAccount(String account, String password) {
        User saved = UserMapper.getUserByAccount(this, account);
        if (saved != null) {
            Toast.makeText(RegisterActivity.this, "账号已存在", Toast.LENGTH_SHORT).show();
            return false;
        }
        User newUser = new User();
        newUser.account = account;
        newUser.password = PasswordEncryptor.encryptPassword(password);
        newUser.username = "用户";
        newUser.avatar = ImageUtils.convertImageToBase64(this, R.drawable.article_image4);
        newUser.background = ImageUtils.convertImageToBase64(this, R.drawable.article_image3);
        UserMapper.insertUser(this,newUser);
        return true;
    }


}
